package com.example.dbmysql.Controller;


import com.example.dbmysql.pojo.Buildings;
import com.example.dbmysql.result.Result;
import com.example.dbmysql.service.BuildingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/buildings")
@Validated
public class buildingsController {
    @Autowired
    private BuildingsService buildingsService;

    @PostMapping("/add")
    public Result addBuildings(@RequestBody Buildings buildings){
        if(buildings.getBon() == null) return  Result.error("楼栋不能为空");
        Buildings b =  buildingsService.findBuildingsByBon(buildings.getBon());
        if( b == null){
            buildingsService.add(buildings);
            return  Result.success();
        }else{
            return  Result.error("楼栋已存在");
        }

    }

    // 正常传递参数 @RequestParam接受  路径传参 使用@PathVariable接受
    @GetMapping("/getbuildings/{id}")
    public Result getBuildings(@PathVariable("id")  Integer id){

        Buildings b =  buildingsService.findBuildingsById(id);
            if(b == null) return Result.error("查询失败");
        return Result.success(b);
    }

    @PutMapping("/update")
    public Result Update(@RequestBody @Validated Buildings buildings){
        Buildings id =  buildingsService.findBuildingsById(buildings.getId());
        if(id == null) return Result.error("更新楼栋不存在");
        if(id.getBon().equals((buildings.getBon()))){
            buildingsService.updata(buildings);
        }else{
            return Result.error("更新楼栋id与实际楼栋不符");
        }


        return Result.success();
    }

    @GetMapping("/getAll")
    public  Result getAll(@RequestParam int page,int pageSize){
        System.out.println(page);
        System.out.println(pageSize);

        List<Buildings> buildings = buildingsService.getAll(page - 1,pageSize);
        // 更具楼栋数字大小进行排序
        buildings.sort(Comparator.comparing(Buildings::getBon));

        return Result.success(buildings);
    }

    @DeleteMapping("/delbuildings")
    public Result delBuildings(@RequestBody Buildings buildings){

        if(buildings.getId() == null)  return Result.error("请传入楼栋id");

        Buildings b =  buildingsService.findBuildingsById(buildings.getId());

        if(b == null) return Result.error("删除楼栋不存在");

        buildingsService.delbuilingsByid(buildings.getId());

        return Result.success();
    }
}
